package simplyrugby.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import simplyrugby.common.Result;
import simplyrugby.entity.Role;
import simplyrugby.mapper.MenuMapper;
import simplyrugby.service.RoleService;

import java.util.List;

@RestController
@RequestMapping("/api/role")
@RequiredArgsConstructor
public class RoleController {
    private final RoleService roleService;
    private final MenuMapper menuMapper;


    @PostMapping
    public Result add(@RequestBody Role role) {
        boolean save = roleService.addRole(role);
        return Result.success().data(save);
    }

    @DeleteMapping("/{id}")
    public Result removeById(@PathVariable String id) {
        boolean b = roleService.removeById(id);
        return Result.success().data(b);
    }

    @PutMapping
    public Result updateById(@RequestBody Role role) {
        boolean flag = roleService.updateRole(role);
        return flag ? Result.success() : Result.fail();
    }


    @GetMapping("/{id}")
    public Result details(@PathVariable String id) {
        Role role = roleService.details(id);
        return Result.success().data(role);
    }

    @GetMapping("/list")
    public Result list() {
        List<Role> list = roleService.list();
        list.forEach(role -> role.setMenuList(menuMapper.selectListByRoleId(role.getId())));
        return Result.success().data(list);
    }

    @PostMapping("/page")
    public Result page(@RequestParam(required = false) Integer pageNum,
                       @RequestParam(required = false) Integer pageSize,
                       @RequestBody Role role
    ) {
        Page<Role> page = roleService.list(pageNum, pageSize, role);
        List<Role> list = page.getRecords().stream().map(r -> {
            return roleService.details(r.getId());
        }).toList();
        page.setRecords(list);
        return Result.success().data(page);
    }
}

